<!doctype html>



  


<html class="theme-next mist use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Nginx,Tomcat," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.2" />






<meta name="description" content="项目使用了Nginx+Tomcat实现动静分离，但之前的配置文件并未做Nginx负载均衡配置，这里做一个简单的测试，实现Nginx负载均衡配置。">
<meta property="og:type" content="article">
<meta property="og:title" content="简单测试 Nginx + Tomcat 实现负载均衡">
<meta property="og:url" content="https://my.oschina.net/u/588736/blog/2016/10/27/nginx+tomcat_loadbalance/index.html">
<meta property="og:site_name" content="晚来风">
<meta property="og:description" content="项目使用了Nginx+Tomcat实现动静分离，但之前的配置文件并未做Nginx负载均衡配置，这里做一个简单的测试，实现Nginx负载均衡配置。">
<meta property="og:image" content="http://7xrn7f.com1.z0.glb.clouddn.com/16-10-27/20650484.jpg">
<meta property="og:image" content="http://7xrn7f.com1.z0.glb.clouddn.com/16-10-27/53893741.jpg">
<meta property="og:image" content="https://static.oschina.net/uploads/img/201610/28164442_OVRF.png">
<meta property="og:updated_time" content="2016-11-28T09:56:24.963Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="简单测试 Nginx + Tomcat 实现负载均衡">
<meta name="twitter:description" content="项目使用了Nginx+Tomcat实现动静分离，但之前的配置文件并未做Nginx负载均衡配置，这里做一个简单的测试，实现Nginx负载均衡配置。">
<meta name="twitter:image" content="http://7xrn7f.com1.z0.glb.clouddn.com/16-10-27/20650484.jpg">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Mist',
    sidebar: {"position":"left","display":"always"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="https://my.oschina.net/u/588736/blog/2016/10/27/nginx+tomcat_loadbalance/"/>


  <title> 简单测试 Nginx + Tomcat 实现负载均衡 | 晚来风 </title>
</head>

<body itemscope itemtype="//schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="//schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">晚来风</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">林花谢了春红，太匆匆。</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="//schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                简单测试 Nginx + Tomcat 实现负载均衡
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-10-27T00:00:00+08:00" content="2016-10-27">
              2016-10-27
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/LoadBalance/" itemprop="url" rel="index">
                    <span itemprop="name">LoadBalance</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>项目使用了Nginx+Tomcat实现动静分离，但之前的配置文件并未做Nginx负载均衡配置，这里做一个简单的测试，实现Nginx负载均衡配置。<br><a id="more"></a></p>
<h2 id="实验环境"><a href="#实验环境" class="headerlink" title="实验环境"></a>实验环境</h2><p>两台虚拟机：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">192.168.137.110</div><div class="line">192.168.137.120</div></pre></td></tr></table></figure>
<h2 id="Tomcat相关修改"><a href="#Tomcat相关修改" class="headerlink" title="Tomcat相关修改"></a>Tomcat相关修改</h2><p>虚拟机中分别安装有tomcat，分别修改webapps/ROOT目录下index.jsp，便于查看实验结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">&lt;!-- 192.168.137.110 --&gt;</div><div class="line">&lt;body&gt;</div><div class="line">        &lt;h1&gt;Tomcat One&lt;/h1&gt;</div><div class="line">  		...</div><div class="line">&lt;/body&gt;</div></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="comment">&lt;!-- 192.168.137.120 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">h1</span>&gt;</span>Tomcat Two<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></div><div class="line">  		...</div><div class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></div></pre></td></tr></table></figure>
<h2 id="Nginx配置"><a href="#Nginx配置" class="headerlink" title="Nginx配置"></a>Nginx配置</h2><p>在192.168.137.110上<a href="http://www.cnblogs.com/dennisit/archive/2012/12/26/2834719.html" target="_blank" rel="external">安装Nginx</a>，修改配置文件：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line">http &#123;</div><div class="line">	...</div><div class="line">	upstream tomcat &#123;</div><div class="line">        server 192.168.137.110:8080;</div><div class="line">        server 192.168.137.120:8080;</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">    server &#123;</div><div class="line">        listen 80;</div><div class="line">        location / &#123;</div><div class="line">        		#proxy_set_header Host $host;</div><div class="line">                proxy_pass         http://tomcat;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">    ...</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="测试"><a href="#测试" class="headerlink" title="测试"></a>测试</h2><p>启动tomcat和Nginx。  </p>
<p>浏览器直接测试效果：</p>
<p><img src="http://7xrn7f.com1.z0.glb.clouddn.com/16-10-27/20650484.jpg" alt=""></p>
<p><img src="http://7xrn7f.com1.z0.glb.clouddn.com/16-10-27/53893741.jpg" alt=""></p>
<p>也可以修改nginx.conf，在server中添加：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">add_header backendIP $upstream_addr;</div><div class="line">add_header backendCode $upstream_status;</div></pre></td></tr></table></figure>
<p>这样就可以在访问页面的时候查看response header中realserver的ip和返回码：</p>
<p><img src="https://static.oschina.net/uploads/img/201610/28164442_OVRF.png" alt=""></p>
<h2 id="Nginx-负载均衡策略"><a href="#Nginx-负载均衡策略" class="headerlink" title="Nginx 负载均衡策略"></a>Nginx 负载均衡策略</h2><h3 id="轮询（默认）"><a href="#轮询（默认）" class="headerlink" title="轮询（默认）"></a>轮询（默认）</h3><p>每个请求按时间顺序逐一分配到不同的后端服务器，如果后端某台服务器宕机，故障系统被自动剔除，使用户访问不受影响。weight默认为1，将请求平均分配给每台服务器，weight可以指定轮询权值，weight值越大，分配到的访问机率越高，主要用于后端每个服务器性能不均的情况下。</p>
<h3 id="IP-hash"><a href="#IP-hash" class="headerlink" title="IP_hash"></a>IP_hash</h3><p>每个请求按访问IP的hash结果分配，这样来自同一个IP的访客固定访问一个后端服务器，有效解决了动态网页存在的session共享问题。当然如果这个节点不可用了，会发到下个节点，而此时没有session同步的话就注销掉了。</p>
<h3 id="最少连接"><a href="#最少连接" class="headerlink" title="最少连接"></a>最少连接</h3><p>将请求分配给连接数最少的服务器。Nginx会统计哪些服务器的连接数最少。会考虑weight的值。</p>
<h3 id="url-hash"><a href="#url-hash" class="headerlink" title="url_hash"></a>url_hash</h3><p>此方法按访问url的hash结果来分配请求，使每个url定向到同一个后端服务器，可以进一步提高后端缓存服务器的效率。Nginx本身是不支持url_hash的，如果需要使用这种调度算法，必须安装Nginx 的hash软件包 nginx_upstream_hash（1.7.2版本以后集成到了nginx源码，不需要单独安装）。</p>
<h3 id="fair"><a href="#fair" class="headerlink" title="fair"></a>fair</h3><p>此种算法可以依据页面大小和加载时间长短智能地进行负载均衡，也就是根据后端服务器的响应时间来分配请求，响应时间短的优先分配。Nginx本身是不支持fair的，如果需要使用这种调度算法，必须下载Nginx的 upstream_fair 模块。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Nginx/" rel="tag">#Nginx</a>
          
            <a href="/tags/Tomcat/" rel="tag">#Tomcat</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/10/19/LVS_Keepalived_MySql_HA/" rel="next" title="双机实现 LVS+Keepalived+MySql 高可用负载均衡环境">
                <i class="fa fa-chevron-left"></i> 双机实现 LVS+Keepalived+MySql 高可用负载均衡环境
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/11/01/VitualBox_RedHat_hostonly/" rel="prev" title="VitualBox使用Host Only方式配置RedHat连接网络">
                VitualBox使用Host Only方式配置RedHat连接网络 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="//schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.gif"
               alt="LenhartG" />
          <p class="site-author-name" itemprop="name">LenhartG</p>
          <p class="site-description motion-element" itemprop="description">美国《时代周刊》2006年度风云人物</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">38</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">14</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">25</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/gxjares" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/u/2526255830" target="_blank" title="Weibo">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  Weibo
                </a>
              </span>
            
          
        </div>

        
        

        
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#实验环境"><span class="nav-number">1.</span> <span class="nav-text">实验环境</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Tomcat相关修改"><span class="nav-number">2.</span> <span class="nav-text">Tomcat相关修改</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Nginx配置"><span class="nav-number">3.</span> <span class="nav-text">Nginx配置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#测试"><span class="nav-number">4.</span> <span class="nav-text">测试</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Nginx-负载均衡策略"><span class="nav-number">5.</span> <span class="nav-text">Nginx 负载均衡策略</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#轮询（默认）"><span class="nav-number">5.1.</span> <span class="nav-text">轮询（默认）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#IP-hash"><span class="nav-number">5.2.</span> <span class="nav-text">IP_hash</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#最少连接"><span class="nav-number">5.3.</span> <span class="nav-text">最少连接</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#url-hash"><span class="nav-number">5.4.</span> <span class="nav-text">url_hash</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#fair"><span class="nav-number">5.5.</span> <span class="nav-text">fair</span></a></li></ol></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div>
<iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="http://music.163.com/outchain/player?type=2&id=208889&auto=1&height=66"></iframe>
</div>
<div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">LenhartG</span>
</div>

<!--
<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>
-->

<!--
<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>
-->
        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.2"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.2"></script>



  



  




  
  

  

  

  

  


</body>
</html>
